package com.kania.simpleemail.setup;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kania.simpleemail.R;
import com.kania.simpleemail.core.IMAP;
import com.kania.simpleemail.maillist.MailListActivity;

public class LoginActivityEx extends Activity {
	private SharedPreferences accountInfo;
	private final String STRING_ACCOUNT_PREFERENCE_NAME = "account_info";
	private String sProvider = "gmail.com";
	private String sID = "";
	private String sPassword = "";
	private String sHost = "imap.gmail.com";
	
	private String sErrorMsg = "";
	
	private View mLoginStatusView;
	
	private EditText editID, editPassword;
	private Button btnCancel, btnLogin;

	LoginTask loginThread;
//	IMAP loginSession;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_ex);
		
		accountInfo = this.getSharedPreferences(STRING_ACCOUNT_PREFERENCE_NAME, Activity.MODE_PRIVATE);

		//debug
//		String sExistAccountList = accountInfo.getString("exist_account", "");
		sID = accountInfo.getString("exist_account", "");
		sPassword = accountInfo.getString("password", "");
		Log.d("KANIA_LOG_LIST", "In Login read pref = " + sID + " / " + sPassword);
		
		//debug
		this.setTitle(sID + " / " + sPassword);
		
		mLoginStatusView = findViewById(R.id.loginStatusView);
		
		editID = (EditText)findViewById(R.id.loginEditIDInput);
		editPassword = (EditText)findViewById(R.id.loginEditPasswordInput);
		sID = "";
		sPassword = "";
		
		btnCancel = (Button)findViewById(R.id.loginBtnCancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
		btnLogin = (Button)findViewById(R.id.loginBtnLogin);
		btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//로그인 처리
				loginThread = (LoginTask) new LoginTask().execute();
			}
		});
		
	}
	
	public class LoginTask extends AsyncTask<Void, Void, Boolean> {
		IMAP loginSession = null;
		boolean bSuccessAccess = false;
		
		@Override
		protected void onPreExecute() {
			//id와 password 를 체크하고
			sID = editID.getText().toString() + "@" + sProvider;
			sPassword = editPassword.getText().toString();
			Log.d("KANIA_LOG_LIST", "In Login read edit = " + sID + " / " + sPassword);
			
			//맞다면
			showProgress(true);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				//세션을 만들고 접근을 시도한 다음
//				loginSession = new IMAP(sHost, sID, sPassword);
				//[130828] changed by singleton parttern using [start]
				loginSession = IMAP.getInstance();
				loginSession.initIMAP(sHost, sID, sPassword);
				//[130828] changed by singleton parttern using [end]
				loginSession.open();
				//이상없이 접근이 성공하였다면 결과값을 세팅하고
				if (loginSession.getFolder().isOpen() == true) {
					bSuccessAccess = true;
				}
				
//				//닫는다
//				loginSession.close();

			} catch (NoSuchProviderException e) {
				Log.e("KANIA_LOG_CORE", "NoSuchProviderException");
				sErrorMsg = "(NoSuchProviderException)";
				bSuccessAccess = false;
			} catch (MessagingException e) {
				Log.e("KANIA_LOG_CORE", "MessagingException");
				sErrorMsg = "(MessagingException)";
				bSuccessAccess = false;
			} finally {
				try {
					loginSession.close();
				} catch (MessagingException e) {
					Log.e("KANIA_LOG_CORE", "MessagingException in close");
					sErrorMsg = "(MessagingException)";
					bSuccessAccess = false;
				}
			}
			return bSuccessAccess;
		}
		
		@Override
		protected void onPostExecute(final Boolean success) {
			showProgress(false);
			if(success) {
				//로그인이 완료되면		
				SharedPreferences.Editor editor = accountInfo.edit();
				String sExistAccountList = accountInfo.getString("exist_account", "");
				
//				if ("".equalsIgnoreCase(sExistAccountList)) {
//					editor.putString("exist_account", sID);
//				} else {
//					editor.putString("exist_account", sExistAccountList + "/" + sID + "@" + sProvider);
//				}
				editor.putString("exist_account", sID);
				editor.putString("password", sPassword);
				editor.commit();
				Log.d("KANIA_LOG_LIST", "In Login save pref = " + sID + " / " + sPassword);
				
				Intent intentMailListActivity = new Intent(LoginActivityEx.this, MailListActivity.class);
				startActivity(intentMailListActivity);
				setResult(RESULT_OK);
				finish();
			} else {
				Toast.makeText(LoginActivityEx.this, "fail to authentiate" + sErrorMsg, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public class LoginAuthentication extends Authenticator{
		@Override
		public PasswordAuthentication getPasswordAuthentication(){
			return new PasswordAuthentication(sID, sPassword);
		}
	}


	private void showProgress(final boolean show) {
		mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
		editID.setEnabled(show ? false : true);
		editPassword.setEnabled(show ? false : true);
		btnCancel.setEnabled(show ? false : true);
		btnLogin.setEnabled(show ? false : true);
	}
}
